package com.webguard.outlierdetection.controller;

import com.webguard.outlierdetection.pojo.Result;
import com.webguard.outlierdetection.service.EmailService;
import jakarta.validation.constraints.Pattern;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@Slf4j//自动定义log
@RestController
@RequestMapping("/email")
@Validated//参数校验
@CrossOrigin
public class EmailController {

    @Autowired
    private EmailService emailService;

    @GetMapping("/sendCode")
    public Result sendCodeEmail(@RequestParam String email) {
        if (!isValidEmail(email)) {
            return Result.error("无效的邮箱格式!");
        }
        int code = emailService.sendCode(email);
        return Result.success(code);
    }

    @GetMapping("/sendText")
    public Result sendTextEmail(@RequestParam String email,@RequestParam String subject, @RequestParam String text) {
        if (!isValidEmail(email)) {
            return Result.error("无效的邮箱格式!");
        }
        emailService.sendSimpleEmail(email,subject,text);
        return Result.success();
    }
    private boolean isValidEmail(String email) {
        // 简单的邮箱格式验证正则表达式
        String emailRegex = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";
        return email.matches(emailRegex);
    }
}
